package moni.anyou.com.view.view.my.invitefamily;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;


import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;

import java.lang.reflect.Field;
import java.util.ArrayList;

import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.base.BaseInfo;
import moni.anyou.com.view.bean.DataClassBean;
import moni.anyou.com.view.bean.InvitedInfo;
import moni.anyou.com.view.bean.SelectFamily;
import moni.anyou.com.view.bean.request.ReqUnbindFBean;
import moni.anyou.com.view.bean.request.ReqsFaimilyNunbersBean;
import moni.anyou.com.view.bean.response.ResFamilyNumer;
import moni.anyou.com.view.config.AnyouerApplication;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.AppTools;
import moni.anyou.com.view.tool.PermissionTools;
import moni.anyou.com.view.tool.ToastTools;
import moni.anyou.com.view.tool.Tools;
import moni.anyou.com.view.view.my.invitefamily.adapter.FamilyNumberAdapter;
import moni.anyou.com.view.widget.NetProgressWindowDialog;
import moni.anyou.com.view.widget.dialog.MessgeDialog;
import moni.anyou.com.view.widget.dialog.PopAddSuccess;
import moni.anyou.com.view.widget.dialog.PopunbindFamily;
import moni.anyou.com.view.wxapi.wxutil.Util;

public class FamilyNumbersActivity extends BaseActivity implements View.OnClickListener {

    RecyclerView rcFamilyNumbers;
    private FamilyNumberAdapter MyAdapter;
    private ArrayList<ResFamilyNumer.RelationBean> numberBeans;
    private PopAddSuccess mPopAddFamilySuccess;
    private PopunbindFamily mPopunbindFamily;
    private NetProgressWindowDialog window;
    private ArrayList<DataClassBean> baseFamily = null;
    private String relativeId;
    private String teamID = "0";
    private String teamName = "";
    //权限
    private int RequestCode = 0x1983;
    MessgeDialog mPDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_family);
        teamID = getIntent().getStringExtra("teamID");
        teamName = getIntent().getStringExtra("teamName");
        initState();
        initWindow();
        init();
    }

    @Override
    public void initView() {
        super.initView();

        initTitlewithCheckbox();
        checkbox.setText("解绑");
        try {
            if (SysConfig.userInfoJson.getInt("recommendId") > 0) {
                checkbox.setVisibility(View.GONE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        window = new NetProgressWindowDialog(mBaseActivity);
        rcFamilyNumbers = (RecyclerView) findViewById(R.id.rc_numbers);
        tvTitle.setText(teamName+"的成员");
        ivBack.setOnClickListener(this);
        getdata();


    }
    @Override
    public void onResume() {
        super.onResume();
        getdata();
    }
    @Override
    public void setData() {
        super.setData();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rcFamilyNumbers.setLayoutManager(gridLayoutManager);
        numberBeans = new ArrayList<>();
        MyAdapter = new FamilyNumberAdapter(this, numberBeans);
        rcFamilyNumbers.setAdapter(MyAdapter);
        initData();
        MyAdapter.notifyDataSetChanged();
       //api = WXAPIFactory.createWXAPI(mContext, "wxcaa9e574ddbd2cf2", false);
        //wxSdkVersion = api.getWXAppSupportAPI();

    }
    //手机高版本样式
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

    private SystemBarTintManager tintManager;
    //手机高版本样式
    @TargetApi(19)
    private void initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.parseColor("#FEC600"));

            tintManager.setStatusBarTintEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(),
                        Color.TRANSPARENT);
            } catch (Exception e) {
            }
        }

    }
    @Override
    public void setAction() {
        super.setAction();
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    checkbox.setText("取消");
                    checkbox.setTextColor(getResources().getColor(R.color.red));
                } else {
                    checkbox.setText("解绑");
                    checkbox.setTextColor(getResources().getColor(R.color.white));

                }
                int size = getList(isChecked).size();

                for (int i = 0; i < size; i++) {
                    SelectFamily tempBean = (SelectFamily) checkBeans.get(i);
                    MyAdapter.notifyItemChanged(tempBean.positon, tempBean.bean);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                onBack();
                break;
            case R.id.btn_commit:
                MyAdapter.notifyItemChanged(mBean.positon, mBean.bean);
                mPopunbindFamily.dismiss();
                break;
            case R.id.btn_unbindcommit:
                getUnbindF(teamID,relativeId);
                mPopunbindFamily.dismiss();
                break;


        }
    }

    public void initData() {
    }

    SelectFamily mBean;

    /**
     * 解绑成员
     *
     * @param bean
     */
    public void removeFamoilyNumbers(SelectFamily bean) {
        mBean = bean;
        relativeId = bean.bean.getUserID();
        mPopunbindFamily = new PopunbindFamily(this, this);
        mPopunbindFamily.showAtLocation(this.findViewById(R.id.pop_need), Gravity.CENTER, 0, 0);
        mPopunbindFamily.isShowing();


    }

    public void addFamoilyNumbers(SelectFamily bean, int position) {

        Intent addNumntent = new Intent();
        addNumntent.putExtra("bean", numberBeans.get(position));
        addNumntent.setClass(mBaseActivity, InviteFriendActivity.class);
        startActivityForResult(addNumntent, 9111);
    }




    ArrayList<SelectFamily> checkBeans = new ArrayList<>();

    /**
     * 获取可删除集合
     *
     * @param isCheck
     * @return
     */
    public ArrayList<SelectFamily> getList(boolean isCheck) {
        checkBeans.clear();
        int size = numberBeans.size();
        for (int i = 0; i < size; i++) {
            ResFamilyNumer.RelationBean tempBean = numberBeans.get(i);
            if (tempBean.status == 1||tempBean.status == 0) {
                tempBean.boolDelete = isCheck;
                checkBeans.add(new SelectFamily(i, tempBean));
            }
        }
        return checkBeans;
    }

    public void getdata() {

        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = new ReqsFaimilyNunbersBean("10", SysConfig.uid, SysConfig.token,teamID).ToJsonString();
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {

                //Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);
                    // Toast.makeText(mContext, t, Toast.LENGTH_LONG).show();
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        numberBeans.clear();
                        ResFamilyNumer Fnumber = new Gson().fromJson(t, ResFamilyNumer.class);
                        ArrayList<ResFamilyNumer.RelationBean> changdataArray = new ArrayList<ResFamilyNumer.RelationBean>();

                        for (int i = 0, size = Fnumber.getList().size(); i < size; i++) {
                            changdataArray.add(new ResFamilyNumer.RelationBean(
                                    Fnumber.getList().get(i).getUserID(),
                                    Fnumber.getList().get(i).getTeamID(),
                                    Fnumber.getList().get(i).getStatus(),
                                    ( Fnumber.getList().get(i).getNick() == null || Fnumber.getList().get(i).getNick().equals("") ? "匿名" : Fnumber.getList().get(i).getNick()),
                                    (Fnumber.getList().get(i).getMobile() == null || Fnumber.getList().get(i).getMobile() .equals("") ? "" : Fnumber.getList().get(i).getMobile() ),
                                    (Fnumber.getList().get(i).getIcon().equals("")
                                            ?"" :Fnumber.getList().get(i).getIcon()),
                                    (Fnumber.getList().get(i).getIsLeader().equals("0") ? "成员" :"领队")));
                        }
                        ResFamilyNumer.RelationBean bean =  new ResFamilyNumer.RelationBean();
                        bean.actionType = "999";
                        bean.setTeamID(teamID);
                        changdataArray.add(bean);
//                        Log.d(TAG, "numbeansize:" + numberBeans.size());
//                        ToastTools.showShort(mContext, "numbeansize:" + numberBeans.size());

                        numberBeans = changdataArray;
                        MyAdapter.setDatas(numberBeans);
                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity, result);
                        }
                        Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_SHORT).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();

                window.closeWindow();
            }
        });
    }

    public void getUnbindF(String teamID,String teamMemberID) {

        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = new ReqUnbindFBean("11", SysConfig.uid, SysConfig.token, teamID,teamMemberID).ToJsonString();
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {

                //Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);
                    //Toast.makeText(mContext, t, Toast.LENGTH_LONG).show();
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        getdata();
                    } else {
                        if (result == -2){
                            AppTools.jumptoLogin(mBaseActivity);
                        }
                        Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_SHORT).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();

                window.closeWindow();
            }
        });
    }






}
